<template>
  <div class="box">
    <FormCom
      :config="formConfig"
      @submitForm="fromSubmit"
      @submitCancel="submitCancel"
    />
    <OptCom
      :config="modalConfig"
      ref="modalCom"
      :selectList="selectList"
      @addSuccess="refresh"
      :editData="editData"
    />
    <TableCom
      ref="table"
      @selection="selection"
      :request="request"
      :config="configTable"
      hasSelection
      :propsTable="{}"
      :options="options"
    />
  </div>
</template>

<script>
import TableCom from "../components/tableCom/index.vue";
import FormCom from "../components/formContainer/index";
import OptCom from "../components/modalCom/index";
import { tableConfig, formConfig, modalConfig } from "./listConfig";
import axios from "axios";
import _ from "loadsh";

export default {
  name: "ListDemo",
  components: {
    TableCom,
    FormCom,
    OptCom,
  },
  data() {
    return {
      request: (params = {}) => {
        return axios.post("/api/page", { ...params }).then((res) => {
          return {
            list: res?.data?.list,
            total: res?.data?.total,
          };
        });
      },
      configTable: {},
      options: {},
      selectList: [],
      formConfig: formConfig,
      modalConfig: modalConfig,
      editData: {},
    };
  },
  methods: {
    init() {
      const obj = _.cloneDeep(tableConfig);
      obj.forEach((e) => {
        if (e.prop === "action") {
          e.render = (scope) => (
            <div>
              <el-button onClick={() => this.edit(scope)} type="text">
                编辑
              </el-button>
              <el-button onClick={() => this.deleteConfim(scope)} type="text">
                删除
              </el-button>
            </div>
          );
        }
      });
      this.configTable = obj;
    },
    handleClick(val) {
      console.log(val);
    },
    async deleteConfim(data) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delete(data);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async delete(data) {
      const res = await axios.post(this.modalConfig.deleteApi, [data?.row?.id]);
      if (res?.data?.code === 200) {
        this.$message({
          type: "success",
          message: "删除成功!",
        });
        this.$refs.table.initData();
      }
    },
    edit(data) {
      this.editData = data?.row;
      this.$refs.modalCom.visible = true;
    },
    refresh() {
      this.$refs.table.initData();
      this.editData = {};
    },
    fromSubmit(val) {
      this.options = val;
    },
    submitCancel() {
      this.options = {};
    },
    selection(val) {
      this.selectList = val;
    },
  },
  mounted() {
    this.init();
  },
};
</script>
